import axios from 'axios'
import type { AxiosRequestConfig,AxiosError,AxiosResponse } from 'axios';
import { ElMessage } from 'element-plus'
import { useUserStore } from '../store/user'
const service = axios.create({
    baseURL: '/api',
    withCredentials: true, 
    timeout: 60000, 
    crossDomain: true
  })

  

  // 请求前置过滤器
  service.interceptors.request.use(
    (config: AxiosRequestConfig) => { 
        // 添加请求头
        const userStore = useUserStore()
        if (userStore.token) {
            config.headers = {
                ...config.headers,
                Authorization: userStore.token
            };
        }
        return config; 
    },
    (error:AxiosError) => {
        console.error('请求拦截器错误:', error);
        return Promise.reject(error); 
    }
);

// 响应前置过滤器
service.interceptors.response.use(
    (response:AxiosResponse) => {
        const res = response.data
        return res
    },
    (error: AxiosError) => {
        if (error.response) {
            const { status } = error.response;
            const userStore = useUserStore()
            switch (status) {
                case 401:
                    ElMessage.error('未授权，请重新登录');
                    userStore.resetToken(); // 调用 logout 方法清除 token
                    break;
                case 403:
                    ElMessage.error('禁止访问');
                    break;
                case 404:
                    ElMessage.error('请求资源不存在');
                    break;
                default:
                    ElMessage.error(`服务器错误：${status}`);
            }
        } else {
            ElMessage.error('网络连接错误，请稍后再试');
        }
        return Promise.reject(error);
    }
);

  export default service